package me.monster.grideaprocessor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @description
 * @author: Created jiangjiwei in 2020/9/30 11:34
 */
class FileUtils {

    private FileUtils() {

    }

    public static FileUtils getInstance() {
        return new FileUtils();
    }

    void saveFile(String content, FileInfo fileInfo) {
        if (fileInfo.isSkip()) {
            copyFile(fileInfo.getSourcePath(), fileInfo.getOutputPath());
        } else {
            save(content, fileInfo.getOutputPath());
        }
    }

    private void copyFile(String sourcePath, String outputPath) {
        checkFileExist(outputPath);
        final File outFile = new File(outputPath);
        if (outFile.exists()) {
            return;
        }
        try {
            Files.copy(new File(sourcePath).toPath(), outFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void save(String content, String path) {
        checkFileExist(path);
        try (final FileWriter fileWriter = new FileWriter(path);
             final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            bufferedWriter.write(content);
            bufferedWriter.flush();
            bufferedWriter.close();
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkFileExist(String filePath) {
        String path = filePath.substring(0, filePath.lastIndexOf("/"));
        File file = new File(path);
        if (file.exists()) {
            file.deleteOnExit();
        } else {
            file.mkdirs();
        }
    }
}
